package com.youngwang.stream;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.google.common.collect.Lists;
import com.youngwang.lambda.Person;

/**
 * Map And FlatMap Stream
 * 
 * @author youngwang
 *
 */
public class MapAndFlatMap {

	public static void main(String[] args) {
		map();
		flatMap();
		optional("asv");
		reduce();
		collectors();
	}

	public static void map() {
		List<Integer> integers = Lists.newArrayList(1, 2, 3, 5);
			List<Integer> squareInteger = integers.stream().map(integer -> integer * integer).collect(Collectors.toList());
		squareInteger.forEach(System.out::println);
	}

	public static void flatMap() {
		Stream<List<Integer>> inputStream = Stream.of(Lists.newArrayList(1), Lists.newArrayList(2, 3),
				Lists.newArrayList(4, 5, 6));
		Stream<Integer> outputStream = inputStream.flatMap(childList -> childList.stream());
		outputStream.forEach(System.out::println);
	}

	public static void optional(String text) {
		Optional.ofNullable(text).ifPresent(System.out::println);
	}

	public static void reduce() {
		String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat);
		System.out.println(concat);

		double minNumber = Stream.of(-1.5, 1.0, 5.0, -4.0).reduce(Double.MAX_VALUE, (Double::min));
		System.out.println(minNumber);

		int sumNumber = Stream.of(1,2,3,4).reduce(0, Integer :: sum);
		System.out.println(sumNumber);

		concat =  Stream.of("a","B","c","D","e","F").filter(x -> x.compareTo("Z") > 0).reduce("-", String :: concat);
		System.out.println(concat);
	}

	public static void collectors(){
		Person[] persons = { new Person("Nie", "Caho", 18), new Person("Lin", "XiaoHui", 25) };
		List<Person> pList = Lists.asList(new Person("Wang", "Yang", 15), persons);
		
		Map<Integer, List<Person>> map = pList.stream().limit(2).collect(Collectors.groupingBy(Person :: getAge));
		for(Map.Entry<Integer, List<Person>> entry : map.entrySet()){
			System.out.println("Age:" + entry.getKey() + " First:" +entry.getValue().get(0).getFirstName()
					+ " Last:"+ entry.getValue().get(0).getLastName());
		}
	}
}
